package com.sdses.weather.converter;

import com.sdses.weather.config.mapping.FieldConverter;
import com.sdses.weather.config.moji.WindDirectionConfig;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

@Component("windDirectionConverter")
@RequiredArgsConstructor
public class WindDirectionConverter implements FieldConverter<String> {

    private final WindDirectionConfig config;

    @Override
    public String convert(Object input, String provider) {

        if (input == null) return "未知风向";

        WindDirectionConfig.ProviderConfig providerConfig = config.getProviderConfig(provider);

        String value = input.toString().trim();

        // 2. 根据 type 处理不同类型
        switch (providerConfig.getType()) {
            case "code":
            case "abbreviation":
            case "chinese-short":
                return providerConfig.getMapping().getOrDefault(value, value);
            case "angle": {
                // 如果是角度，需要转换为方向（可选）
                try {
                    double angle = Double.parseDouble(value);
                    return angleToDirection(angle);
                } catch (NumberFormatException e) {
                    return "未知风向";
                }
            }
            default:
                return providerConfig.getMapping().getOrDefault(value, value);
        }
    }

    // 角度转风向（360° → 16方位）
    private String angleToDirection(double angle) {
        String[] directions = {
                "北风", "北东北风", "东北风", "东东北风",
                "东风", "东东南风", "东南风", "南东南风",
                "南风", "南西南风", "西南风", "西西南风",
                "西风", "西西北风", "西北风", "北西北风"
        };
        int index = (int) Math.round((angle % 360) / 22.5) % 16;
        return directions[index];
    }
}